package org.molamil.acto.commands {
	import flash.utils.getQualifiedClassName;
	import flash.errors.IllegalOperationError;
	import flash.events.EventDispatcher;
	import org.molamil.acto.core.loggers.Logger;	
	
	/**
	 * XXX: Document.
	 * 
	 * @author Jorge Hernandez
	 */
	public class AbstractCommandFactory extends EventDispatcher implements CommandFactory {
		
		
		// PROPERTIES
		
		private static var log:Logger = Logger.getLogger("SimpleCommandFactory");
	
		private var commandList:Array; // of CommandContext
	
	
		// CONSTRUCTOR
		
		public function AbstractCommandFactory(commandList:Array = null) {
			
			// Abstract check.
			if (getQualifiedClassName(this) == "org.molamil.acto.commands::AbstractCommandFactory")
            	throw new IllegalOperationError("AbstractCommandFactory must be extended");
			
			this.commandList = new Array();
			if (commandList != null) {
				for each (var commandContext:CommandContext in commandList)
					createCommand(commandContext, false);
			}
			
		}
	
		// PUBLIC METHODS
		
		public function createCommand(context:CommandContext, checkConsistency:Boolean = true):void {
			
			//TODO: Add checks for minimum required information.
			//TODO: Set defaults.
			
			if (context.id == null) {
				log.warning("The context for the command to create needs to have a valid id, the new page command not be created.");
				return;
			}
			
			if (containsCommand(context.id)) {
				log.warning("There is already a command with id \"{id}\", the new command will not be created.".replace("{id}", context.id));
				return;
			}
			
			commandList.push(context);
			
			//TODO: Implement consistency/processors.
			
			var event:CommandsEvent = new CommandsEvent(CommandsEvent.COMMAND_CONTEXT_CREATED, false, false, null, context);
			dispatchEvent(event);
			
		}
		
		public function removeCommand(id:String, checkConsistency:Boolean = true):void {
			//TODO: Implement.
		}
		
		public function containsCommand(id:String):Boolean {
			var b:Boolean = getCommand(id) != null;
			log.debug("containsCommand(), id = " + id + ": " + b);
			return b;
		}
		
		public function getCommand(id:String):CommandContext {
			
			log.info("getCommand(), id = " + id);
		
			var commandContext:CommandContext = null;
			
			for (var i:uint = 0; i < commandList.length; i++) {
				var cc:CommandContext = commandList[i];
				if (cc.id == id) {
					commandContext = cc;
					break;
				}
			}
			
			if (commandContext == null)
				log.info("The requested command with id '" + id + "' does not exist");
				
			return commandContext;
		
		}
		
		public function getCommands():Array {
			log.info("getCommands(), returning " + commandList.length);
			return commandList;
		}
		
		
	}
	
}